package com.qd.qx.im;

import java.util.Timer;
import java.util.TimerTask;

import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.XMPPConnection;

import android.util.Log;

import com.qd.qx.api.MyXMPPTCPConnection;
import com.qd.qx.bean.UserData;

/**
 * Code is far away from bug with the animal protecting
 * Author：YS on 2018/10/18
 * Function：连接监听类
 */
public class TaxiConnectionListener implements ConnectionListener {
    private Timer tExit;
    private String username;
    private String password;
    private int logintime = 2000;

    @Override
    public void connected(XMPPConnection connection) {

    }

    @Override
    public void authenticated(XMPPConnection connection, boolean resumed) {

    }

    @Override
    public void connectionClosed() {
        Log.i("TaxiConnectionListener", "連接關閉");
        // 關閉連接
        MyXMPPTCPConnection.getInstance().getConnection().disconnect();
        // 重连服务器
        if (MyXMPPTCPConnection.getInstance().isConnectAuto()) {
            tExit = new Timer();
            tExit.schedule(new timetask(), logintime);
        }
    }

    @Override
    public void connectionClosedOnError(Exception e) {
        Log.i("TaxiConnectionListener", "連接關閉異常");
        // 判斷為帳號已被登錄
        boolean error = e.getMessage().equals("stream:error (conflict)");
        if (!error) {
            // 關閉連接
            MyXMPPTCPConnection.getInstance().getConnection().disconnect();
            // 重连服务器
            if (MyXMPPTCPConnection.getInstance().isConnectAuto()) {
                tExit = new Timer();
                tExit.schedule(new timetask(), logintime);
            }
        }
    }

    class timetask extends TimerTask {
        @Override
        public void run() {
            username = UserData.getInstance().getLoginName();
            password = UserData.getInstance().getPassword();
            if (username != null && password != null) {
                Log.i("TaxiConnectionListener", "嘗試登錄");
                // 连接服务器
                MyXMPPTCPConnection.getInstance().login(username, password);
            }
        }
    }

    @Override
    public void reconnectingIn(int arg0) {
    }

    @Override
    public void reconnectionFailed(Exception arg0) {
    }

    @Override
    public void reconnectionSuccessful() {
    }
}